package com.ccut.xunfeiSpringboot.controller;

import com.ccut.xunfeiSpringboot.service.AvatarService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/avatar")
public class AvatarController {

    private final AvatarService avatarService;

    public AvatarController(AvatarService avatarService) {
        this.avatarService = avatarService;
    }

    @PostMapping("/start")
    public ResponseEntity<?> startSession(@RequestParam("round") int round) {
        try {
            avatarService.startSession(round);
            return ResponseEntity.ok("Session started for round " + round);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(e.getMessage());
        }
    }

    @PostMapping("/text")
    public ResponseEntity<?> sendText(@RequestBody String text) {
        try {
            avatarService.sendText(text);
            return ResponseEntity.ok("Text sent");
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(e.getMessage());
        }
    }

    @PostMapping("/audio")
    public ResponseEntity<?> sendAudio(@RequestBody byte[] audioData) {
        try {
            avatarService.sendAudio(audioData);
            return ResponseEntity.ok("Audio sent");
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(e.getMessage());
        }
    }

    @PostMapping("/stop")
    public ResponseEntity<?> stopSession() {
        avatarService.stopSession();
        return ResponseEntity.ok("Session stopped");
    }

    @GetMapping("/message")
    public ResponseEntity<?> getMessage() {
        String message = avatarService.getReceivedMessage();
        if (message != null) {
            return ResponseEntity.ok(message);
        } else {
            return ResponseEntity.ok("No message received yet");
        }
    }
}